package com.nd.android.musicboxlibrary.ui.view;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.common.utils.StarAppUtils;
import com.nd.android.musicboxlibrary.R;
import com.nd.android.musicboxlibrary.business.comm.MagicNumber;
import com.nd.android.musicboxlibrary.util.Log;
import com.nd.android.musicboxlibrary.util.TimeUtil;

/**
 * 下拉刷新列表控件
 * 
 * @author 慕容秋 (muroqiu@qq.com)
 */
public class PullToRefreshListView extends ListView implements OnScrollListener, MagicNumber {
    
    /**
     * 
     * <br>Created 2014年11月28日 上午12:05:46
     * @author       wat.ztag
    */
    @Override
    public void initMagicNumber() {}
    
    private final static String TAG = "CustomListView";

    private final static int RELEASE_To_REFRESH = 0;

    private final static int PULL_To_REFRESH = 1;

    // 正在刷新
    private final static int REFRESHING = 2;

    // 刷新完成
    private final static int DONE = 3;

    private final static int LOADING = 4;

    // 实际的padding的距离与界面上偏移距离的比例
    private final static int RATIO = 2;

    private LayoutInflater inflater;

    private LinearLayout headView;

    private LinearLayout footView;

    private TextView tipsTextview;

    private TextView lastUpdatedTextView;

    private ImageView arrowImageView;

    private ProgressBar progressBar;

    private RotateAnimation animation;

    private RotateAnimation reverseAnimation;

    private ProgressBar footerProgessBar;

    private TextView footerTextView;

    // 用于保证startY的值在一个完整的touch事件中只被记录一次
    private boolean isRecored;

    private int headContentWidth;

    private int headContentHeight;

    private int startY;

    private int firstItemIndex;

    private int lastItem;

    private int state;

    private boolean isBack;

    private OnRefreshListener mRefreshListener;

    private OnLoadNextPageListener mLoadNextPageListener;

    private boolean isRefreshable;

    public final static int PAGE_ITEM_COUNT = 10;

    private int totolItemCount = 0;

    private boolean isAbleLoadNextPage = false;

    private boolean isLoadingNextPage = false;

    private Context mContext;

    int i = 1;

    private boolean isSearch = false;

    // private DealListAdapter mAdapter;

    private int mLastFirstVisibleItem;

    public static final int SCRLL_DIRECTION_UP = 1;

    public static final int SCRLL_DIRECTION_NONE = 0;

    public static final int SCRLL_DIRECTION_DOWN = -1;

    private OnScrollListener mScrollListener = null;

    /**
     * Creates a new instance of PullToRefreshListView. <br>
     * Created 2014年9月11日 下午11:46:22
     * 
     * @param context Context
     */
    public PullToRefreshListView(Context context) {
        super(context);
        mContext = context;
        init(context);
    }

    /**
     * Creates a new instance of PullToRefreshListView. <br>
     * Created 2014年9月11日 下午11:46:25
     * 
     * @param context Context
     * @param attrs AttributeSet
     */
    public PullToRefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init(context);
    }

    /**
     * 设置是否可刷新
     * 
     * @param refreshable boolean
     */
    public void setRefreshable(boolean refreshable) {
        isRefreshable = refreshable;
        if (isRefreshable) {
            footView.setVisibility(View.VISIBLE);
            headView.setVisibility(View.VISIBLE);
        } else {
            footView.setVisibility(View.GONE);
            headView.setVisibility(View.GONE);
        }
    }

    /**
     * 获取刷新状态
     * 
     * @return boolean
     */
    public boolean getRefreshable() {
        return isRefreshable;
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:46:37
     * 
     * @param context Context
     * @author wat.ztag
     */
    private void init(Context context) {
        setCacheColorHint(context.getResources().getColor(R.color.mbx_transparent));
        inflater = LayoutInflater.from(context);

        headView = (LinearLayout) inflater.inflate(R.layout.mbx_list_view_header, null);

        arrowImageView = (ImageView) headView.findViewById(R.id.head_arrowImageView);
        arrowImageView.setMinimumWidth(n70);
        arrowImageView.setMinimumHeight(n50);
        progressBar = (ProgressBar) headView.findViewById(R.id.head_progressBar);
        tipsTextview = (TextView) headView.findViewById(R.id.head_tipsTextView);
        lastUpdatedTextView = (TextView) headView.findViewById(R.id.head_lastUpdatedTextView);
        measureView(headView);
        headContentHeight = headView.getMeasuredHeight();
        headContentWidth = headView.getMeasuredWidth();

        headView.setPadding(0, -1 * headContentHeight, 0, 0);
        headView.invalidate();

        Log.v("size", "width:" + headContentWidth + " height:" + headContentHeight);
        footView = (LinearLayout) inflater.inflate(R.layout.mbx_list_view_footer, null);

        footerProgessBar = (ProgressBar) footView.findViewById(R.id.progressBar_footer);
        footerTextView = (TextView) footView.findViewById(R.id.text_footer);
        addHeaderView(headView, null, false);
        addFooterView(footView, null, false);
        setOnScrollListener(this);

        animation = new RotateAnimation(0, nm180, RotateAnimation.RELATIVE_TO_SELF, f0_5,
                RotateAnimation.RELATIVE_TO_SELF, f0_5);
        animation.setInterpolator(new LinearInterpolator());
        animation.setDuration(n250);
        animation.setFillAfter(true);

        reverseAnimation = new RotateAnimation(nm180, 0, RotateAnimation.RELATIVE_TO_SELF, f0_5,
                RotateAnimation.RELATIVE_TO_SELF, f0_5);
        reverseAnimation.setInterpolator(new LinearInterpolator());
        reverseAnimation.setDuration(n200);
        reverseAnimation.setFillAfter(true);

        state = DONE;
        isRefreshable = false;
        //字体
        StarAppUtils.setViewTypeFace(tipsTextview, false);
        StarAppUtils.setViewTypeFace(lastUpdatedTextView, false);
        StarAppUtils.setViewTypeFace(footerTextView, false);
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:46:41
     * 
     * @return OnScrollListener
     * @author wat.ztag
     */
    public OnScrollListener getScrollListener() {
        return mScrollListener;
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:46:45
     * 
     * @param scrollListener OnScrollListener
     * @author wat.ztag
     */
    public void setScrollListener(OnScrollListener scrollListener) {
        this.mScrollListener = scrollListener;
    }

    @Override
    public void addFooterView(View v) {
        super.addFooterView(v);
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:46:48
     * 
     * @param arg0 AbsListView
     * @param firstVisiableItem int
     * @param visibleItemCount int
     * @param totalItemCount int
     * @author wat.ztag
     */
    public void onScroll(AbsListView arg0, int firstVisiableItem, int visibleItemCount,
            int totalItemCount) {
        firstItemIndex = firstVisiableItem;
        this.totolItemCount = totalItemCount;
        lastItem = firstVisiableItem + visibleItemCount - getHeaderViewsCount();
        Log.i(TAG, "onScroll===lastItem:" + lastItem);
        if (lastItem > getFooterViewsCount() && mLoadNextPageListener != null && isAbleLoadNextPage) {
            if (lastItem >= totolItemCount - getHeaderViewsCount()) {
                footerProgessBar.setVisibility(View.VISIBLE);
                // this.setAbleLoadNextPage(false);
                // setFooterText(mContext.getString(R.string.download_next_page));
                this.mLoadNextPageListener.onLoadNextPage();
                // isLoadingNextPage = true;
            } else {
                footerProgessBar.setVisibility(View.INVISIBLE);
                setFooterText("");
            }
        }

        final int currentFirstVisibleItem = getFirstVisiblePosition();
        if (currentFirstVisibleItem > mLastFirstVisibleItem) {
            if (mScrollListener != null) {
                mScrollListener.onScroll(SCRLL_DIRECTION_DOWN);

            }
        } else if (currentFirstVisibleItem < mLastFirstVisibleItem) {
            if (mScrollListener != null) {
                mScrollListener.onScroll(SCRLL_DIRECTION_UP);
            }
        }
        mLastFirstVisibleItem = currentFirstVisibleItem;

    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:46:51
     * 
     * @author wat.ztag
     */
    public void setNotLoadingNextpage() {
        isLoadingNextPage = false;
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:46:55
     * 
     * @param text String
     * @author wat.ztag
     */
    public void setFooterText(String text) {
        if (text != null && text.length() > 0) {
            footerTextView.setVisibility(View.VISIBLE);
        } else {
            footerTextView.setVisibility(View.INVISIBLE);
        }
        footerTextView.setText(text);
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:47:02
     * 
     * @param view AbsListView
     * @param scrollState int
     * @author wat.ztag
     */
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        Log.i(TAG, "onScrollStateChanged===pageItemCount:" + PAGE_ITEM_COUNT + " lastItem:"
                + lastItem + " totolItemCount:" + totolItemCount + " headerviewcount:"
                + getHeaderViewsCount() + " scrollState:" + scrollState + " footerviewcount:"
                + getFooterViewsCount());

        // final int currentFirstVisibleItem = getFirstVisiblePosition();
        //
        // if (currentFirstVisibleItem > mLastFirstVisibleItem) {
        // if (scrollListener != null) {
        // scrollListener.onScroll(SCRLL_DIRECTION_DOWN);
        // }
        // } else if (currentFirstVisibleItem < mLastFirstVisibleItem) {
        // if (scrollListener != null) {
        // scrollListener.onScroll(SCRLL_DIRECTION_UP);
        // }
        // }
        // mLastFirstVisibleItem = currentFirstVisibleItem;

        // if (mAdapter != null) {
        // switch (scrollState) {
        // case SCROLL_STATE_FLING:
        // mAdapter.setScrolling(true);
        // break;
        // case SCROLL_STATE_TOUCH_SCROLL:
        // mAdapter.setScrolling(true);
        // break;
        // case SCROLL_STATE_IDLE:
        // mAdapter.setScrolling(false);
        // mAdapter.notifyDataSetChanged();
        // break;
        // default:
        // break;
        // }
        // }
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:47:06
     * 
     * @param needToast boolean
     * @author wat.ztag
     */
    public void forceRefresh(boolean needToast) {
        if (state != REFRESHING) {
            state = REFRESHING;
            changeHeaderViewByState();
            onRefresh(needToast);
        }
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:47:09
     * 
     * @param event MotionEvent
     * @return boolean
     * @author wat.ztag
     */
    public boolean onTouchEvent(MotionEvent event) {
        if (isRefreshable) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (firstItemIndex == 0 && !isRecored) {
                    isRecored = true;
                    startY = (int) event.getY();
                    Log.v(TAG, "在down时候记录当前位置‘");
                }
                break;
            case MotionEvent.ACTION_UP:
                if (state != REFRESHING && state != LOADING) {
                    if (state == DONE) {
                        System.out.println(state == DONE);
                    }
                    if (state == PULL_To_REFRESH) {
                        state = DONE;
                        changeHeaderViewByState();

                        Log.v(TAG, "由下拉刷新状态，到done状态");
                    }
                    if (state == RELEASE_To_REFRESH) {
                        state = REFRESHING;
                        changeHeaderViewByState();
                        onRefresh(true);
                        Log.v(TAG, "由松开刷新状态，到done状态");
                    }
                }
                isRecored = false;
                isBack = false;
                break;
            case MotionEvent.ACTION_MOVE:
                int tempY = (int) event.getY();
                if (!isRecored && firstItemIndex == 0) {
                    Log.v(TAG, "在move时候记录下位置");
                    isRecored = true;
                    startY = tempY;
                }
                if (state != REFRESHING && isRecored && state != LOADING) {
                    if (state == RELEASE_To_REFRESH) {
                        setSelection(0);
                        if (((tempY - startY) / RATIO < headContentHeight) && (tempY - startY) > 0) {
                            state = PULL_To_REFRESH;
                            changeHeaderViewByState();
                            Log.v(TAG, "由松开刷新状态转变到下拉刷新状态");
                        } else if (tempY - startY <= 0) {
                            state = DONE;
                            changeHeaderViewByState();
                            Log.v(TAG, "由松开刷新状态转变到done状态");
                        } else {
                            Log.i("else");
                        }
                    }
                    if (state == PULL_To_REFRESH) {
                        setSelection(0);
                        // 下拉到可以进入RELEASE_TO_REFRESH的状态
                        if ((tempY - startY) / RATIO >= headContentHeight) {
                            state = RELEASE_To_REFRESH;
                            isBack = true;
                            changeHeaderViewByState();
                            Log.v(TAG, "由done或者下拉刷新状态转变到松开刷新");
                        } else if (tempY - startY <= 0) {
                            state = DONE;
                            changeHeaderViewByState();
                            Log.v(TAG, "由DOne或者下拉刷新状态转变到done状态");
                        }
                    }
                    // done状态下
                    if (state == DONE) {
                        if (tempY - startY > 0) {
                            state = PULL_To_REFRESH;
                            changeHeaderViewByState();
                        }
                    }
                    // 更新headView的size
                    if (state == PULL_To_REFRESH) {
                        headView.setPadding(0, -1 * headContentHeight + (tempY - startY) / RATIO,
                                0, 0);
                    }
                    // 更新headView的paddingTop
                    if (state == RELEASE_To_REFRESH) {
                        headView.setPadding(0, (tempY - startY) / RATIO - headContentHeight, 0, 0);
                    }
                }
                break;
            default:
                break;
            }
        }
        return super.onTouchEvent(event);
    }
    // 当状态改变时候，调用该方法，以更新界面
    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:47:12
     * 
     * @author wat.ztag
     */
    private void changeHeaderViewByState() {
        switch (state) {
        case RELEASE_To_REFRESH:
            arrowImageView.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.GONE);
            tipsTextview.setVisibility(View.VISIBLE);
            lastUpdatedTextView.setVisibility(View.VISIBLE);

            arrowImageView.clearAnimation();
            arrowImageView.startAnimation(animation);

            tipsTextview.setText(mContext.getString(R.string.mbx_release_to_refresh));

            Log.v(TAG, "当前状态，松开刷新");
            break;
        case PULL_To_REFRESH:
            progressBar.setVisibility(View.GONE);
            tipsTextview.setVisibility(View.VISIBLE);
            lastUpdatedTextView.setVisibility(View.VISIBLE);
            arrowImageView.clearAnimation();
            arrowImageView.setVisibility(View.VISIBLE);
            // 是由RELEASE_To_REFRESH状态转变来的
            if (isBack) {
                isBack = false;
                arrowImageView.clearAnimation();
                arrowImageView.startAnimation(reverseAnimation);

                tipsTextview.setText(mContext.getString(R.string.mbx_pull_to_refresh));
            } else {
                tipsTextview.setText(mContext.getString(R.string.mbx_pull_to_refresh));
            }
            Log.v(TAG, "当前状态，下拉刷新");
            break;

        case REFRESHING:

            headView.setPadding(0, 0, 0, 0);

            progressBar.setVisibility(View.VISIBLE);
            arrowImageView.clearAnimation();
            arrowImageView.setVisibility(View.GONE);
            if (isSearch) {
                tipsTextview.setText(mContext.getString(R.string.mbx_refreshing));
            } else {
                tipsTextview.setText(mContext.getString(R.string.mbx_refreshing));
            }
            lastUpdatedTextView.setVisibility(View.VISIBLE);

            Log.v(TAG, "当前状态,正在刷新...");
            break;
        case DONE:
            headView.setPadding(0, -1 * headContentHeight, 0, 0);

            progressBar.setVisibility(View.GONE);
            arrowImageView.clearAnimation();
            arrowImageView.setImageResource(R.drawable.mbx_arrow);
            tipsTextview.setText(mContext.getString(R.string.mbx_pull_to_refresh));
            lastUpdatedTextView.setVisibility(View.VISIBLE);

            if (isSearch) {
                isRefreshable = false;
            }

            Log.v(TAG, "当前状态，done");
            break;
        default:
            break;
        }
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:47:15
     * 
     * @param refreshListener OnRefreshListener
     * @author wat.ztag
     */
    public void setonRefreshListener(OnRefreshListener refreshListener) {
        this.mRefreshListener = refreshListener;
        isRefreshable = true;
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:47:20
     * 
     * @version PullToRefreshListView
     * @author wat.ztag
     * 
     * @see
     */
    public interface OnRefreshListener {
        /**
         * 
         * <br>
         * Created 2014年9月11日 下午11:47:27
         * 
         * @param needToast boolean
         * @author wat.ztag
         */
        void onRefresh(boolean needToast);
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:47:32
     * 
     * @param loadNextPageListener OnLoadNextPageListener
     * @author wat.ztag
     */
    public void setonLoadNextPageListener(OnLoadNextPageListener loadNextPageListener) {
        this.mLoadNextPageListener = loadNextPageListener;
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:47:37
     * 
     * @version PullToRefreshListView
     * @author wat.ztag
     * 
     * @see
     */
    public interface OnLoadNextPageListener {
        /**
         * 
         * <br>
         * Created 2014年9月11日 下午11:47:41
         * 
         * @author wat.ztag
         */
        void onLoadNextPage();
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:45:27
     * 
     * @author wat.ztag
     */
    public void onRefreshComplete() {
        state = DONE;
        lastUpdatedTextView.setText(TimeUtil.format2EventTime(TimeUtil.getCurrentTime()));
        changeHeaderViewByState();
        Log.v(TAG, "onRefreshComplete() 被调用。。。");
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:45:35
     * 
     * @param info String
     * @author wat.ztag
     */
    public void onRefreshComplete(String info) {
        state = DONE;
        lastUpdatedTextView.setText(info);
        changeHeaderViewByState();
        Log.v(TAG, "onRefreshComplete() 被调用。。。");
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:45:42
     * 
     * @param needToast boolean
     * @author wat.ztag
     */
    private void onRefresh(boolean needToast) {
        if (mRefreshListener != null) {
            mRefreshListener.onRefresh(needToast);
        }
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:45:48
     * 
     * @version PullToRefreshListView
     * @author wat.ztag
     * 
     * @see
     */
    public interface OnScrollListener {
        /**
         * 
         * <br>
         * Created 2014年9月11日 下午11:46:01
         * 
         * @param direction int
         * @author wat.ztag
         */
        void onScroll(int direction);
    }

    // 此方法直接照搬自网络上的一个下拉刷新的demo，此处是“估计”headView的width以及height
    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:46:11
     * 
     * @param child View
     * @author wat.ztag
     */
    private void measureView(View child) {
        ViewGroup.LayoutParams p = child.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        }
        child.measure(childWidthSpec, childHeightSpec);
    }

    //
    // public void setAdapter(BaseAdapter adapter) {
    // lastUpdatedTextView.setText(TimeUtil.format2EventTime(TimeUtil.getCurrentTime()));
    // super.setAdapter(adapter);
    // try {
    // mAdapter = (DealListAdapter)adapter;
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:46:15
     * 
     * @param isable boolean
     * @author wat.ztag
     */
    public void setAbleLoadNextPage(boolean isable) {
        isAbleLoadNextPage = isable;
        if (!isable) {
            footerProgessBar.setVisibility(View.GONE);
            if (totolItemCount > getHeaderViewsCount() + getFooterViewsCount()) {
                setFooterText("");
            }
        }
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:46:18
     * 
     * @return boolean
     * @author wat.ztag
     */
    public boolean getAbleLoadNextPage() {
        return isAbleLoadNextPage;
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        try {
            super.dispatchDraw(canvas);
        } catch (Exception e) {
            android.util.Log.e("CustomThemeListView", "list dispatchDraw error:" + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void buildDrawingCache() {
        try {
            super.buildDrawingCache();
        } catch (Exception e) {
            android.util.Log.e("CustomThemeListView",
                    "list buildDrawingCache error:" + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void buildDrawingCache(boolean autoScale) {
        try {
            super.buildDrawingCache(autoScale);
        } catch (Exception e) {
            android.util.Log.e("CustomThemeListView",
                    "list buildDrawingCache_autoScale error:" + e.getMessage());
            e.printStackTrace();
        }
    }

}
